package utils;

import models.TA001;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * Created by xuyang on 2018/3/20.
 */
public class TemplateSplittor {
    private String template;
    private String datagramText;

    public TemplateSplittor(String template, String datagramText) {
        this.template = template;
        this.datagramText = datagramText;
    }

    public Document invoke() {

        String fixedText = ACARS620Parser.clearDatagramControlChar(datagramText);


        Document doc = DocumentHelper.createDocument();
        Element dataElem = null;
        try {
            TA001 acars = ACARS620Parser.parse(fixedText);
            dataElem = TemplateMatcher.templateSplitResultFor(template, acars.getFreeText());
            if (dataElem != null) {
                doc.add(dataElem);
            } else {
                doc.addElement("Nope");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            doc.addElement("error").setText(e.getLocalizedMessage());
        } catch (ACARS620Exception e) {
            e.printStackTrace();
            doc.addElement("error").setText(e.getLocalizedMessage());
        }
        return doc;
    }
}
